<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-100 via-gray-100 to-pink-100">
    <div class="container mx-auto px-4 py-8">
      <h1 class="text-3xl font-extrabold text-center mb-6 text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-pink-500">
        测试结果查看
      </h1>
      
      <div v-if="isLoading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
      
      <div v-else-if="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
        <strong class="font-bold">错误！</strong>
        <span class="block sm:inline">{{ error }}</span>
      </div>
      
      <div v-else-if="simulationHistory.length === 0" class="bg-white rounded-xl shadow-md p-8 text-center">
        <svg class="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <h2 class="text-xl font-bold text-gray-700 mb-2">暂无测试结果</h2>
        <p class="text-gray-500 mb-4">请先进行模拟测试后再来查看结果</p>
        <router-link to="/simulation" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
          去模拟测试
        </router-link>
      </div>
      
      <!-- 筛选和排序选项 -->
      <div v-else class="bg-white rounded-xl shadow-md p-6 mb-6">
        <div class="flex flex-wrap gap-4 justify-between items-center">
          <div class="flex space-x-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">排序方式</label>
              <select v-model="sortOption" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="time-desc">时间 (最新优先)</option>
                <option value="time-asc">时间 (最早优先)</option>
                <option value="profit-desc">盈利 (从高到低)</option>
                <option value="profit-asc">盈利 (从低到高)</option>
                <option value="rounds-desc">局数 (从多到少)</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">主打方向</label>
              <select v-model="mainChoiceFilter" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="all">全部</option>
                <option value="player">闲</option>
                <option value="banker">庄</option>
              </select>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">搜索策略名称</label>
            <input 
              v-model="searchQuery" 
              type="text" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="输入关键字搜索"
            >
          </div>
        </div>
      </div>
      
      <!-- 模拟历史记录列表 -->
      <div v-if="filteredSimulations.length > 0" class="bg-white rounded-xl shadow-md p-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold text-gray-800">历史模拟 ({{ filteredSimulations.length }}个)</h2>
          <button 
            @click="clearAllSimulations"
            class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
          >
            清空历史模拟
          </button>
        </div>
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">策略名称</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总局数</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">盈亏</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">主打方向</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">胜/负</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="sim in filteredSimulations" :key="sim.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ sim.id }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ sim.strategy_name }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ sim.total_rounds }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm" :class="sim.net_profit > 0 ? 'text-green-600 font-medium' : 'text-red-500 font-medium'">
                  {{ sim.net_profit > 0 ? '+' : '' }}{{ sim.net_profit }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm" :class="getMainChoiceClass(sim.main_choice)">
                  {{ sim.main_choice === 'player' ? '闲' : (sim.main_choice === 'banker' ? '庄' : '未确定') }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ sim.win_rounds }}/{{ sim.lose_rounds }}
                  <span class="text-xs ml-1">
                    ({{ ((sim.win_rounds / (sim.win_rounds + sim.lose_rounds || 1)) * 100).toFixed(1) }}%)
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(sim.timestamp) }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 space-x-2">
                  <button 
                    @click="viewResults(sim.id)"
                    class="text-blue-600 hover:text-blue-800 font-medium"
                  >
                    查看结果
                  </button>
                  <button 
                    @click="clearSimulation(sim.id)"
                    class="text-red-600 hover:text-red-800 font-medium"
                  >
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <div v-else-if="!isLoading && simulationHistory.length > 0" class="bg-white rounded-xl shadow-md p-8 text-center">
        <svg class="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <h2 class="text-xl font-bold text-gray-700 mb-2">没有符合条件的结果</h2>
        <p class="text-gray-500 mb-4">请尝试修改筛选条件</p>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../logic/api'

export default {
  name: 'ResultsListPage',
  data() {
    return {
      simulationHistory: [],
      isLoading: true,
      error: null,
      searchQuery: '',
      sortOption: 'time-desc',
      mainChoiceFilter: 'all'
    }
  },
  computed: {
    filteredSimulations() {
      let result = [...this.simulationHistory]
      
      // 应用主打方向筛选
      if (this.mainChoiceFilter !== 'all') {
        result = result.filter(sim => sim.main_choice === this.mainChoiceFilter)
      }
      
      // 应用搜索筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(sim => 
          sim.strategy_name.toLowerCase().includes(query) || 
          sim.id.toString().includes(query)
        )
      }
      
      // 应用排序
      result.sort((a, b) => {
        switch(this.sortOption) {
          case 'time-asc':
            return new Date(a.timestamp) - new Date(b.timestamp)
          case 'profit-desc':
            return b.net_profit - a.net_profit
          case 'profit-asc':
            return a.net_profit - b.net_profit
          case 'rounds-desc':
            return b.total_rounds - a.total_rounds
          case 'time-desc':
          default:
            return new Date(b.timestamp) - new Date(a.timestamp)
        }
      })
      
      return result
    }
  },
  mounted() {
    this.fetchSimulationHistory()
  },
  methods: {
    async fetchSimulationHistory() {
      try {
        this.isLoading = true
        const data = await api.simulations.getAll()
        this.simulationHistory = data
      } catch (error) {
        console.error('获取模拟历史失败', error)
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    
    async clearAllSimulations() {
      if (!confirm('确定要清空所有历史模拟记录吗？此操作不可恢复。')) {
        return
      }
      
      try {
        this.isLoading = true
        await api.simulations.clearAll()
        alert('所有历史模拟记录已清空')
        this.simulationHistory = []
      } catch (error) {
        console.error('清空历史模拟记录失败', error)
        alert(`清空失败: ${error.message}`)
      } finally {
        this.isLoading = false
      }
    },
    
    async clearSimulation(simulationId) {
      if (!confirm(`确定要删除ID为${simulationId}的模拟记录吗？此操作不可恢复。`)) {
        return
      }
      
      try {
        this.isLoading = true
        await api.simulations.clearById(simulationId)
        alert(`模拟记录${simulationId}已删除`)
        // 从列表中移除该记录
        this.simulationHistory = this.simulationHistory.filter(sim => sim.id !== simulationId)
      } catch (error) {
        console.error('删除模拟记录失败', error)
        alert(`删除失败: ${error.message}`)
      } finally {
        this.isLoading = false
      }
    },
    
    viewResults(simulationId) {
      this.$router.push(`/simulation-result/${simulationId}`)
    },
    
    getMainChoiceClass(mainChoice) {
      if (mainChoice === 'player') return 'text-blue-600'
      if (mainChoice === 'banker') return 'text-red-600' 
      return 'text-gray-500'
    },
    
    formatDate(dateString) {
      try {
        const date = new Date(dateString)
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return dateString
        }
        return new Intl.DateTimeFormat('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }).format(date)
      } catch (e) {
        // 如果格式化失败，返回原始字符串
        return dateString
      }
    }
  }
}
</script> 